package com.rzjm.exercise.module.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.config.ProjectUrlConfig;
import com.rzjm.exercise.common.enums.ExcelType;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.*;
import com.rzjm.exercise.common.utils.encryp.impl.MD5Utils;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.domain.excel.DeviceDataExcel;
import com.rzjm.exercise.module.domain.excel.ShopExcel;
import com.rzjm.exercise.module.domain.excel.ShopNewExcel;
import com.rzjm.exercise.module.domain.excel.SysUserExcel;
import com.rzjm.exercise.module.service.*;
import com.rzjm.exercise.sys.core.dict.domain.DictDO;
import com.rzjm.exercise.sys.core.dict.service.DictService;
import com.rzjm.exercise.sys.core.file.domain.FileDO;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import com.rzjm.exercise.sys.system.user.service.UserService;
import com.vdurmont.emoji.EmojiParser;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 企业
 *
 * @author mr.zhou
 * @email zhouwei_nice@163.com
 * @date 2020-12-15 22:36:23
 */
@Controller
@RequestMapping("/module/shop")
public class ShopController extends BaseController {
    @Resource
    private ShopService shopService;
    @Resource
    private ProjectUrlConfig projectUrlConfig;
    @Resource
    private WxUserService wxUserService;
    @Resource
    private DeviceService deviceService;
    @Resource
    private DeviceNodeService deviceNodeService;
    @Resource
    private TerminalTemperatureService terminalTemperatureService;
    @Resource
    private DeviceWeldingService deviceWeldingService;
    @Resource
    private UserService userService;
    @Resource
    private DictService dictService;
    @Resource
    private TownsService townsService;
    @Resource
    private PianqusService pianqusService;
    @Resource
    private GroupsService groupsService;
    @Resource
    private UserShopRelationService userShopRelationService;
    @Resource
    private ShopTypeService shopTypeService;
    @Resource
    private ShopTypeRelationService shopTypeRelationService;
    @Resource
    private DeviceRangeService deviceRangeService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private DistrictService districtService;
    @Resource
    private CityService cityService;
    @Resource
    private PlatformService platformService;
    @Resource
    private TemperatureLimitService temperatureLimitService;
    @Resource
    private CarWeeksService carWeeksService;
    @Resource
    private CarLimitTimesService carLimitTimesService;

    @Value("${projecturl.imgurl}")
    private String imgurl;

    @Value("${projecturl.uploadPath}")
    private String uploadPath;

    @Log("查询企业页面")
    @GetMapping()
    @RequiresPermissions(value = {"module:shop:shop","module:shop:fireworks"}, logical = Logical.OR )
    String Shop1(Model model) {
        UserDO user = getUser();
        QueryWrapper<Pianqus> qw = new QueryWrapper<>();
        if(user.getUserType() == 2) {//集团用户
            qw.eq("jituan_id", user.getGroupId());
        } else if(user.getUserType() >= 3) {//集团用户
            qw.eq("id", user.getPianquId());
        }
        List<Pianqus> pianquses = pianqusService.list(qw);
        model.addAttribute("pianquses",pianquses);
        return "module/shop/shop";
    }

    @Log("查询企业页面")
    @GetMapping("/tempValueList/{limitId}")
    @RequiresPermissions(value = {"module:shop:shop","module:shop:fireworks"}, logical = Logical.OR )
    String tempValueList(Model model, @PathVariable("limitId") Integer limitId) {
        UserDO user = getUser();
        QueryWrapper<Pianqus> qw = new QueryWrapper<>();
        if(user.getUserType() == 2) {//集团用户
            qw.eq("jituan_id", user.getGroupId());
        } else if(user.getUserType() >= 3) {//集团用户
            qw.eq("id", user.getPianquId());
        }
        List<Pianqus> pianquses = pianqusService.list(qw);
        model.addAttribute("pianquses",pianquses);
        model.addAttribute("limitId",limitId);
        return "module/shop/shopTempList";
    }


    @Log("查询企业页面")
    @GetMapping("/pianqu/{pianquId}")
    String pianquList(Model model, @PathVariable("pianquId") Integer pianquId) {
        model.addAttribute("pianquId", pianquId);

        UserDO user = getUser();
        QueryWrapper<Pianqus> qw = new QueryWrapper<>();
        if(user.getUserType() == 2) {//集团用户
            qw.eq("jituan_id", user.getGroupId());
        } else if(user.getUserType() >= 3) {//集团用户
            qw.eq("id", user.getPianquId());
        }
        List<Pianqus> pianquses = pianqusService.list(qw);
        model.addAttribute("pianquses",pianquses);

        return "module/shop/shop";
    }

    @Log("查询企业页面")
    @GetMapping("/dashboard")
    @RequiresPermissions(value = {"module:shop:shop"}, logical = Logical.OR )
    String dashboard(Model model) {
        Map<String, Object> map = new HashMap<>();
        map.put("jituan_user_id", 2);
        List<Shop> shops = shopService.getPageByUserId(map);
        model.addAttribute("shops", shops);
        return "module/shop/dashboard1";
    }

    @Log("查询企业页面")
    @GetMapping("/{shopType}")
    @RequiresPermissions(value = {"module:shop:shop","module:shop:fireworks"}, logical = Logical.OR )
    String Shop(Model model,@PathVariable(value = "shopType",required = false) Integer shopType) {
        model.addAttribute("shopType",shopType);
        if(shopType == 3){
            return "module/shop/firework";
        }

        UserDO user = getUser();
        QueryWrapper<Pianqus> qw = new QueryWrapper<>();
        if(user.getUserType() == 2) {//集团用户
            qw.eq("jituan_id", user.getGroupId());
        } else if(user.getUserType() >= 3) {//集团用户
            qw.eq("id", user.getPianquId());
        }
        List<Pianqus> pianquses = pianqusService.list(qw);
        model.addAttribute("pianquses",pianquses);

        return "module/shop/shop";
    }

    @Log("查询企业页面")
    @GetMapping("/wxadmin/{shopId}")
    @RequiresPermissions("module:shop:shop")
    String ShopWxAdmin(Model model,@PathVariable("shopId") Integer shopId) {
        model.addAttribute("shopId",shopId);
        return "module/shop/admin/admin";
    }

    @Log("查询企业")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions(value = {"module:shop:shop","module:shop:fireworks"}, logical = Logical.OR )
    public DataTableLayUI<Shop> list(DataTableLayUI<Shop> condition) {
        UserDO userDO = getUser();
        Map<String,Object> map = condition.getSearchParams();
        String shopName = null;
        Integer shopType = null;
        Integer deviceType = null;
        Integer isFire= 0;
        if(map != null) {
            shopName = StrUtil.isNotEmpty(map.get("search_like_shopName").toString()) ? map.get("search_like_shopName").toString():null;
            shopType = StrUtil.isNotEmpty(map.get("search_eq_shopType").toString()) ? Integer.parseInt(map.get("search_eq_shopType").toString()):null;
            deviceType = map.containsKey("search_eq_deviceType") && StrUtil.isNotEmpty(map.get("search_eq_deviceType").toString()) ? Integer.parseInt(map.get("search_eq_deviceType").toString()):null;
            isFire = StrUtil.isNotEmpty(map.get("search_eq_isFire").toString()) ? Integer.parseInt(map.get("search_eq_isFire").toString()):0;
        }
        String pianquId = map.containsKey("search_eq_pianquId") &&  StrUtil.isNotEmpty(map.get("search_eq_pianquId").toString()) ? map.get("search_eq_pianquId").toString() : null;
        String positionType = map.containsKey("search_eq_positionType") &&  StrUtil.isNotEmpty(map.get("search_eq_positionType").toString()) ? map.get("search_eq_positionType").toString() : null;
        Map<String,Object> map1 = new HashMap<>();
        if(shopName != null){
            map1.put("shop_name",shopName);
        }
        if(shopType != null){
            map1.put("shop_type",shopType);
        }
        if(pianquId != null){
            map1.put("pianqu_id",pianquId);
        }
        map1.put("isFire",isFire);
        if(userDO.getUserType() == 2){
            map1.put("group_id",userDO.getGroupId());
        }else if(userDO.getUserType() == 3){//分区管理员
            map1.put("pianqu_id",userDO.getPianquId());
        }
        else if(userDO.getUserType() == 12){
            map1.put("sys_user_id",userDO.getUserId());
        } else if(userDO.getUserType() == 13|| userDO.getUserType() == 14){//
            map1.put("jituan_user_id",userDO.getGroupId());
        }
        else if(userDO.getUserType() == 4 ||userDO.getUserType() == 5 || userDO.getUserType() == 6 || userDO.getUserType() == 7 || userDO.getUserType() == 10){//分厂和 巡检人员
            map1.put("id",userDO.getShopId());
        }

        Page<Shop> page = shopService.getPage(condition);
        List<Shop> list = new ArrayList<>();
        if(userDO.getUserType() == 0 || userDO.getUserType() == 1){
//            if (shopType != null && shopType == 4 && "2".equals(positionType)){
//                page = new Page<Shop>(1, 99999);
//            }
            list = shopService.getPageByAdminUserId(page,map1);
        }else{
            list = shopService.getPageByUserId(page,map1);
        }
//        List<Integer> shopIds = list.stream().map(s -> s.getId()).collect(Collectors.toList());
//        if (shopType != null && shopType == 4 && "2".equals(positionType)){ // 锅炉测温
////            if (shopIds != null && shopIds.size() > 0){
//                condition.getSearchParams().put("shopIds", shopIds);
//                DataTableLayUI<Shop> dt = shopService.getShopDeviceCountListPage(condition);
//                return dt;
////            }else {
////                return new DataTableLayUI<Shop>();
////            }
//
//        }else {
            DataTableLayUI<Shop> dt = shopService.pageSearchCustom(page,list,condition);
            if(dt != null){
                List<Shop> shops = dt.getData();
                for (Shop shop : shops){
                    shop.setQrcodeImg(imgurl + shop.getQrcodeImg());

                    Pianqus pianqus = pianqusService.getById(shop.getPianquId());
                    if(pianqus!= null){
                        shop.setPianquName(pianqus.getPianquName());
                    }

                    if(shopType!= null){
                        if(shopType == 5){
                            QueryWrapper<DeviceRange> qw0 = new QueryWrapper<>();
                            qw0.eq("device_type", 0);
                            qw0.eq("shop_id", shop.getId());
                            long device0Count = deviceRangeService.count(qw0);
                            shop.setDevice0Count(device0Count);


                            QueryWrapper<DeviceRange> qw1 = new QueryWrapper<>();
                            qw1.eq("device_type", 1);
                            qw1.eq("shop_id", shop.getId());
                            long device1Count = deviceRangeService.count(qw1);
                            shop.setDevice1Count(device1Count);
                        } else if(shopType == 6){

                            QueryWrapper<DeviceWelding> qw0 = new QueryWrapper<>();
                            if (deviceType != null){
                                qw0.eq("device_type", deviceType);
                            }
                            qw0.eq("shop_id", shop.getId());
                            long device0Count = deviceWeldingService.count(qw0);
                            shop.setDeviceCount(device0Count);

                        }else{
                            if(shop.getDeviceShowType() == 0){
                                QueryWrapper<Device> qwDevice = new QueryWrapper<>();
                                qwDevice.eq("shop_id", shop.getId());
                                if (deviceType != null){
                                    qwDevice.eq("device_type", deviceType);
                                }
                                if (positionType != null && Integer.parseInt(positionType) != 0){
                                    qwDevice.eq("position_type", positionType);
                                }
                                long deviceCount = deviceService.count(qwDevice);
                                shop.setDeviceCount(deviceCount);
                            }else{
                                QueryWrapper<DeviceNode> qwDevice = new QueryWrapper<>();
                                qwDevice.eq("shop_id", shop.getId());
                                if (deviceType != null){
                                    qwDevice.eq("device_type", deviceType);
                                }
                                if (positionType != null && Integer.parseInt(positionType) != 0){
                                    qwDevice.eq("position_type", positionType);
                                }
                                long deviceCount = deviceNodeService.count(qwDevice);
                                shop.setDeviceCount(deviceCount);
                            }
                        }
                    }
                    else {
                        if (shop.getDeviceShowType() == 0) {
                            QueryWrapper<Device> qwDevice = new QueryWrapper<>();
                            qwDevice.eq("shop_id", shop.getId());
                            if (deviceType != null){
                                qwDevice.eq("device_type", deviceType);
                            }
                            if (positionType != null && Integer.parseInt(positionType) != 0){
                                qwDevice.eq("position_type", positionType);
                            }
                            long deviceCount = deviceService.count(qwDevice);
                            shop.setDeviceCount(deviceCount);
                        } else {
                            QueryWrapper<DeviceNode> qwDevice = new QueryWrapper<>();
                            qwDevice.eq("shop_id", shop.getId());
                            if (deviceType != null){
                                qwDevice.eq("device_type", deviceType);
                            }
                            if (positionType != null && Integer.parseInt(positionType) != 0){
                                qwDevice.eq("position_type", positionType);
                            }
                            long deviceCount = deviceNodeService.count(qwDevice);
                            shop.setDeviceCount(deviceCount);
                        }
                    }
                }
            }
            return dt;
//        }

    }


    /**
     *  根据制粒机温度的设备，查询对应下的企业列表
     * @param condition
     * @return
     */
    @Log("查询企业")
    @ResponseBody
    @GetMapping("/listByDeviceTemp")
    @RequiresPermissions(value = {"module:shop:shop","module:shop:fireworks"}, logical = Logical.OR )
    public DataTableLayUI<Shop> listByDeviceTemp(DataTableLayUI<Shop> condition) {
        UserDO userDO = getUser();
        Map<String,Object> map = condition.getSearchParams();
        String limitId = null;
        if(map != null) {
            limitId = StrUtil.isNotEmpty(map.get("limitId").toString()) ? map.get("limitId").toString():null;
        }
        Map<String,Object> map1 = new HashMap<>();
        map1.put("deviceType",2);
        map1.put("groupId", userDO.getGroupId());

        TemperatureLimit limit = temperatureLimitService.findById(limitId);
        if(limit != null){
            map1.put("valueType", limit.getIsRange());
            if(limit.getIsRange() == 0){
                map1.put("currentValue", limit.getMinValue());
            } else if(limit.getIsRange() == 1){
                map1.put("minValue", limit.getMinValue());
                map1.put("maxValue", limit.getMaxValue());
            } else if(limit.getIsRange() == 2){
                map1.put("currentValue", limit.getMinValue());
            }
        }

        Page<Shop> page = shopService.getPage(condition);
        List<Shop> list = shopService.getShopListByWenduValue(page,map1);
        DataTableLayUI<Shop> dt = shopService.pageSearchCustom(page,list,condition);
        if(dt != null){
            List<Shop> shops = dt.getData();
            for (Shop shop : shops){
                shop.setQrcodeImg(imgurl + shop.getQrcodeImg());
                Pianqus pianqus = pianqusService.getById(shop.getPianquId());
                if(pianqus!= null){
                    shop.setPianquName(pianqus.getPianquName());
                }

                QueryWrapper<DeviceNode> qwDevice = new QueryWrapper<>();
                qwDevice.eq("shop_id", shop.getId());
                qwDevice.eq("device_type", 2);
                long deviceCount = deviceNodeService.count(qwDevice);
                shop.setDeviceCount(deviceCount);
            }
        }
        return dt;
    }

    @Log("查询企业")
    @ResponseBody
    @GetMapping("/list/firework")
    @RequiresPermissions(value = {"module:shop:fireworks"}, logical = Logical.OR )
    public DataTableLayUI<Shop> fireworkList(DataTableLayUI<Shop> condition) {
        DataTableLayUI<Shop> dt = shopService.pageSearchLayUI(condition);
        if(dt != null){
            List<Shop> shops = dt.getData();
            shops.forEach(shop ->{
                shop.setQrcodeImg(imgurl + shop.getQrcodeImg());
            });
        }
        return dt;
    }

    @Log("查询企业微信管理员列表")
    @ResponseBody
    @GetMapping("/admin/list")
    @RequiresPermissions("module:shop:shop")
    public DataTableLayUI<WxUser> adminList(DataTableLayUI<WxUser> condition) {
        DataTableLayUI<WxUser> dt = wxUserService.pageSearchLayUI(condition);
        return dt;
    }

    @PostMapping(value = "/getList")
    @ResponseBody
    public R getList(Shop shop) {
        QueryWrapper<Shop> qw = new QueryWrapper<>();
        qw.ne("state", 3);
        List<Shop> list = shopService.list(qw);
        return R.ok(0,list);
    }

    @Log("新增企业页面")
    @GetMapping("/add/fire")
    @RequiresPermissions("module:shop:add")
    String addFire(Model model) {
        Shop shop = new Shop();
        shop.setState(0);
        shop.setIsFire(1);

        model.addAttribute("shop", shop);

        List<ShopType> shopTypes = shopTypeService.selectAllList();

        model.addAttribute("shopTypesJson", JSONUtil.parseArray(shopTypes).toString());

        model.addAttribute("shopTypes", shopTypes);

        return "module/shop/detail";
    }

    @Log("新增企业页面")
    @GetMapping("/add")
    @RequiresPermissions("module:shop:add")
    String add(Model model) {
        UserDO user = getUser();
        Shop shop = new Shop();
        shop.setState(0);
        shop.setIsFire(0);

        model.addAttribute("shop", shop);

        List<ShopType> shopTypes = shopTypeService.selectAllList();

        model.addAttribute("shopTypesJson", JSONUtil.parseArray(shopTypes).toString());

        model.addAttribute("shopTypes", shopTypes);

        QueryWrapper<Pianqus> qw = new QueryWrapper<>();
        if(user.getUserType() > 1) {//集团用户
            qw.eq("jituan_id", user.getGroupId());
        }
        List<Pianqus> pianquses = pianqusService.list(qw);
        for (Pianqus pianqu : pianquses){
            Groups groups = groupsService.findById(pianqu.getJituanId());
            if(groups!= null){
                pianqu.setJituanName(groups.getGroupName());
            }
        }
        model.addAttribute("pianquList", pianquses);

        return "module/shop/detail";
    }

    @Log("编辑企业页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("module:shop:edit")
    String edit(@PathVariable("id") Integer id, Model model) {

        UserDO user = getUser();
        List<ShopType> shopTypes = shopTypeService.selectAllList();

        Shop shop = shopService.findById(id);
        if(shop!=null){
            if(shop.getShopLogo()!=null){
                FileDO file = new FileDO();
                file.setUrl(projectUrlConfig.getImgurl() + shop.getShopLogo());
                shop.setShopLogoFile(file);
            }

            for (ShopType shopType : shopTypes){
                QueryWrapper<ShopTypeRelation> qw = new QueryWrapper<>();
                qw.eq("shop_id",shop.getId());
                qw.eq("shop_type", shopType.getTypeValue());
                qw.last("limit 1");
                ShopTypeRelation typeRelation = shopTypeRelationService.getOne(qw);
                if(typeRelation != null){
                    shopType.setIsCheck(typeRelation.getState());
                }else{
                    shopType.setIsCheck(0);
                }
            }
        }


        QueryWrapper<Pianqus> qw = new QueryWrapper<>();
        if(user.getUserType() > 1) {//集团用户
            qw.eq("jituan_id", user.getGroupId());
        }
        List<Pianqus> pianquses = pianqusService.list(qw);
        for (Pianqus pianqu : pianquses){
            Groups groups = groupsService.findById(pianqu.getJituanId());
            if(groups!= null){
                pianqu.setJituanName(groups.getGroupName());
            }
        }
        model.addAttribute("pianquList", pianquses);

        model.addAttribute("shop", shop);

        model.addAttribute("shopTypesJson", JSONUtil.parseArray(shopTypes).toString());
        model.addAttribute("shopTypes", shopTypes);
        return "module/shop/detail";
    }

    @Log("编辑企业页面")
    @GetMapping("/editTicket/{id}")
    @RequiresPermissions("module:shop:edit")
    String editTicket(@PathVariable("id") Integer id, Model model) {
        Shop shop = shopService.findById(id);

        model.addAttribute("shop", shop);

        List<UserDO> users = userService.selectListByColumn("shop_id", id);

        model.addAttribute("users", users);

        return "module/shop/detailTicket";
    }

    @GetMapping("/carTuisongren/{id}")
    @RequiresPermissions("module:shop:edit")
    String carTuisongren(@PathVariable("id") Integer id, Model model) {
        Shop shop = shopService.findById(id);

        model.addAttribute("shop", shop);

        List<UserDO> users = userService.selectListByColumn("shop_id", id);

        model.addAttribute("users", users);

        return "module/shop/carTuisongren";
    }

    @Log("审核企业页面")
    @GetMapping("/goCheck/{id}")
    @RequiresPermissions("module:shop:check")
    String goCheck(@PathVariable("id") Integer id, Model model) {
        Shop shop = shopService.findById(id);
        model.addAttribute("shop", shop);
        return "module/shop/check";
    }

    /**
     * 重置二维码
     */
    @Log("重置二维码")
    @PostMapping("/resetQrcode")
    @ResponseBody
    @RequiresPermissions("module:shop:edit")
    public R resetQrcode( Integer id) {
        Shop shop = shopService.findById(id);
        if(shop!=null){
            try{
                String qrType = "shop";
                if(shop.getIsFire() == 1){
                    qrType = "firework";
                }
                int upload_type = OssUtil.TYPE_SHOP_PHOTOS;
                String fileName = "shop_qr_"+shop.getShopNo()+".jpg";

//                String content = "{\"qrtype\":\""+qrType+"\",\"num\":\""+shop.getShopNo()+"\"}";
//                Aes aes = new Aes();
//                content = aes.encrypt(content);
                String content = "";
                if(shop.getIsFire() == 1){// 烟花爆竹商铺  可用微信扫码
                    content = "https://en.zcchengyi.com/wxmini/fire/qr?num=" + shop.getShopNo();
                }else{
                    content = "{\"qrtype\":\""+qrType+"\",\"num\":\""+shop.getShopNo()+"\"}";
                    Aes aes = new Aes();
                    content = aes.encrypt(content);
                }

                System.out.println("content:  "+ content);
                //上传头像到OSS
                String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                QRCodeUtilEx.createQrCodeImg(content, shop.getShopName(), null, uploadPath +"/"+img_key, true);
                shop.setQrcodeImg(img_key);
            }catch (Exception ex){
                ex.printStackTrace();
            }
            if (shopService.updateById(shop)) {
                return R.ok();
            }
        }
        return R.error();
    }

    /**
     * 保存
     */
    @Log("新增设备")
    @GetMapping("/download/{shopNo}")
    public void download(@PathVariable("shopNo") String shopNo, HttpServletResponse response) {
        Shop shop = shopService.selectByUniqueColumn("shop_no",shopNo);
        if(shop!=null){
            FileUtils.download(uploadPath + shop.getQrcodeImg(),response);
        }
    }

    /**
     *@author by  zhouwei
     *@createtime: 2017/9/11 17:49
     *@Description：获取所有技能种类的列表
     *@modifytime:
     */
    @RequestMapping(value="/searchUserList")
    @ResponseBody
    public String searchUserList(@RequestParam String keywords){
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        try{
            QueryWrapper<WxUser> qw = new QueryWrapper<>();
            qw.like("nick_name",keywords);
            List<WxUser> userList = wxUserService.list(qw);
            for (WxUser p : userList){
                if(p.getNickName()!=null){
                    p.setNickName(EmojiParser.parseToUnicode(p.getNickName()));
                }
            }
            jsonArray = JSONUtil.parseArray(userList);
            jsonObject.set("code","00");
            jsonObject.set("count",userList.size());
            jsonObject.set("data",jsonArray);

        }catch(Exception e){
            jsonObject.set("code","01");
        }
        String ret = jsonObject.toString();
        return ret;
    }

    /**
     * 保存
     */
    @Log("新增企业")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("module:shop:add")
    public R save(@Valid Shop shop) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        String shopNo = "M"+(calendar.getTime().getTime());
        shop.setDistrictId(0);
        shop.setLatitude(0d);
        shop.setLongitude(0d);
        shop.setDistrictId(0);
        shop.setShopNo(shopNo);
        shop.setState(1);
        shop.setShopType(1);
        shop.setCreateTime(new Date());

        Pianqus pianqus = pianqusService.getById(shop.getPianquId());
        if(pianqus!= null){
            shop.setGroupId(pianqus.getJituanId());
        }

        try{
            int upload_type = OssUtil.TYPE_SHOP_PHOTOS;
            String fileName = "shop_qr_" + shop.getShopNo()+".jpg";
            String content = "";
            if(shop.getIsFire() == 1){// 烟花爆竹商铺  可用微信扫码
                content = "https://en.zcchengyi.com/wxmini/fire/qr?num=" + shopNo;
            }else{
                content = "{\"qrtype\":\"shop\",\"num\":\""+shop.getShopNo()+"\"}";
                Aes aes = new Aes();
                content = aes.encrypt(content);
            }
            System.out.println("content:  "+ content);
            //上传头像到OSS
            String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
            QRCodeUtilEx.createQrCodeImg(content, shop.getShopName(), null, uploadPath + "/" + img_key, true);
            shop.setQrcodeImg(img_key);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        boolean ret = shopService.save(shop);
        if(ret){
            if(shop.getHidShopTypes() != null){
                JSONArray hidShopTypes = JSONUtil.parseArray(shop.getHidShopTypes());
//                List<ShopType> shopTypes = JSONUtil.toList(JSONUtil.toJsonStr(hidShopTypes),ShopType.class);
                for (int i = 0 ;i<hidShopTypes.size();i++){
                    JSONObject jsonObject = hidShopTypes.getJSONObject(i);
                    ShopType shopType = JSONUtil.toBean(jsonObject.toString(),ShopType.class);
                    if(shopType!= null){
                        QueryWrapper<ShopTypeRelation> qw = new QueryWrapper<>();
                        qw.eq("shop_id",shop.getId());
                        qw.eq("shop_type", shopType.getTypeValue());
                        qw.last("limit 1");
                        ShopTypeRelation typeRelation = shopTypeRelationService.getOne(qw);
                        if(typeRelation == null){
                            typeRelation = new ShopTypeRelation();
                            typeRelation.setShopId(shop.getId());
                            typeRelation.setShopType(shopType.getTypeValue());
                            typeRelation.setState(shopType.getIsCheck());
                            typeRelation.setTypeName(shopType.getTypeName());
                            shopTypeRelationService.save(typeRelation);
                        }else{
                            typeRelation.setState(shopType.getIsCheck());
                            typeRelation.setTypeName(shopType.getTypeName());
                            shopTypeRelationService.updateById(typeRelation);
                        }
                    }
                }
            }


            UserDO user = getUser();
            if(user != null){
                UserShopRelation relation = new UserShopRelation();
                if(user.getUserType() == 2){// 集团管理员添加企业
                    relation.setJituanUserId(user.getUserId());
                    relation.setSysUserId(user.getUserId());
                }else if(user.getUserType() == 3){// 片区管理员添加企业
                    relation.setJituanUserId(user.getJituanId());
                    relation.setSysUserId(user.getUserId());
                }
                relation.setShopId(shop.getId());
                boolean bl = userShopRelationService.save(relation);
                if(bl){
                    return R.ok();
                }else{
                    return R.error();
                }
            }
        }
        return R.error();
    }

    @Log("批量新增企业页面")
    @GetMapping("/goBatchAddUser")
    @RequiresPermissions("module:shop:importUser")
    String goBatchAdd() {
        return "module/shop/upload_user";
    }

    @Log("批量新增企业页面")
    @GetMapping("/goBatchAddShop")
    @RequiresPermissions("module:shop:importShop")
    String goBatchAddShop() {
        return "module/shop/upload_shop";
    }


    @GetMapping("/goBatchAddDianhan")
    @RequiresPermissions("module:company:import")
    String goBatchAdd(Model model) {
        List<Platform> list = platformService.list();
        model.addAttribute("platformList", list);
        return "module/shop/upload_dianhan";
    }

    /**
     *  批量导入巡查人员信息
     * @param file
     */
    @RequestMapping(value = "/readExcelBatchAddUser", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("module:shop:importUser")
    Object readExcel(@RequestParam(value="file", required = false) MultipartFile file){
        long t1 = System.currentTimeMillis();
        List<SysUserExcel> list = ExcelUtils.readExcel("", SysUserExcel.class, file);
        long t2 = System.currentTimeMillis();
        System.out.println(String.format("read over! cost:%sms", (t2 - t1)));
        list.forEach(b -> {
            Shop shop = shopService.selectByUniqueColumn("shop_name",b.getShopName());
            if(shop != null){
                UserDO userDO = userService.selectByUniqueColumn("username",b.getPhoneNum());
                if(userDO == null){
                    userDO = new UserDO();
                    userDO.setGroupId(userDO.getGroupId());
                    userDO.setUsername(b.getPhoneNum());
                    if(b.getRoleName().equals("维修")){
                        userDO.setUserType(6);
                        userDO.setRoleId(7);
                    }else if(b.getRoleName().equals("巡检")){
                        userDO.setUserType(5);
                        userDO.setRoleId(6);
                    }
                    userDO.setPassword(MD5Utils.encrypt(userDO.getUsername(), "123456"));
                    userDO.setMobile(b.getPhoneNum());
                    userDO.setName(b.getRealName());
                    userDO.setStatus(1);
                    userDO.setShopId(shop.getId());
                    userService.save(userDO);
                }
            }
        });
        return R.ok();
    }

    @RequestMapping(value = "/readExcelBatchAddNew", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("module:shop:importShop")
    Object readExcelBatchAddNew(@RequestParam(value = "file", required = false) MultipartFile file,
                                @RequestParam("platformId") Integer platformId) {
        try{

            if(platformId == null || platformId == 0){
                return R.error("请选择所属平台");
            }
            List<ShopNewExcel> list = ExcelUtils.readExcel("shop", ShopNewExcel.class, file);
            if (list.size() == 0) {
                return R.error("excel模板不正确,请检查后导入！");
            }
            Date date = new Date();
            List<DictDO> companyTypeList = dictService.listByType("company_type");
            List<ShopNewExcel> errorList = new ArrayList<>();
//            String preCompanyType = null;
            String preTownName = null;
            for (int i = 0; i < list.size(); i++) {
                ShopNewExcel companyExcel = list.get(i);
                if(StrUtil.isEmpty(companyExcel.getCompanyName())){
                    continue;
                }
                Shop c = new Shop();
//                if (StringUtils.isNotBlank(companyExcel.getCompanyTypeName())) {
//                    preCompanyType = companyExcel.getCompanyTypeName();
//                } else {
//                    c.setCompanyTypeName(preCompanyType);
//                }
                if (StringUtils.isNotBlank(companyExcel.getTownName())) {
                    preTownName = c.getTownName();
                } else {
                    c.setTownName(preTownName);
                }
                if (StringUtils.isBlank(companyExcel.getTownName()) || StringUtils.isBlank(companyExcel.getCompanyName())) {
                    companyExcel.setCompanyName(companyExcel.getCompanyName() + "(乡镇名称为空)");
                    errorList.add(companyExcel);
                    continue;
                }
                QueryWrapper<Shop> qw = new QueryWrapper<>();
                qw.eq("shop_name", companyExcel.getCompanyName());
                qw.eq("platform_id", platformId);
                qw.last("limit 1");
                Shop oldCompany = shopService.getOne(qw);
                if (oldCompany != null) {
//                    c.setId(oldCompany.getId());
                    c = oldCompany;
                } else {
                    c = new Shop();
                    c.setShopName(companyExcel.getCompanyName());
                    c.setPlatformId(platformId);
                    c.setState(1);
                    c.setCreateTime(date);

                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    String shopNo = "M"+(calendar.getTime().getTime());
                    c.setShopNo(shopNo);

                    try{
                        int upload_type = OssUtil.TYPE_SHOP_PHOTOS;
                        String fileName = "shop_qr_" + c.getShopNo()+".jpg";
                        String content = "";
                        if(c.getIsFire() == 1){// 烟花爆竹商铺  可用微信扫码
                            content = "https://en.zcchengyi.com/wxmini/fire/qr?num=" + shopNo;
                        }else{
                            content = "{\"qrtype\":\"shop\",\"num\":\""+c.getShopNo()+"\"}";
                            Aes aes = new Aes();
                            content = aes.encrypt(content);
                        }
                        System.out.println("content:  "+ content);
                        //上传头像到OSS
                        String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                        QRCodeUtilEx.createQrCodeImg(content, c.getShopName(), null, uploadPath + "/" + img_key, true);
                        c.setQrcodeImg(img_key);
                    }catch (Exception ex){
                        ex.printStackTrace();
                    }
                }
                c.setSocialCode(companyExcel.getSocialCode());
                c.setLegalPerson(companyExcel.getLegalPerson());
                c.setLegalPhone(companyExcel.getLegalPhone());
                c.setAddress(companyExcel.getAddress());
                c.setBuildDate(companyExcel.getBuildDate());
                c.setHeadman(companyExcel.getHeadman());
                c.setTelphone(companyExcel.getHeadmanPhone());
                c.setIsOpenFace(0);
                c.setIsUpload(2);

//                for (int j = 0; j < companyTypeList.size(); j++) {
//                    DictDO companyType = companyTypeList.get(j);
//                    if(c.getCompanyTypeName() != null){
//                        if (companyType.getName().contains(companyExcel.getCompanyTypeName())) {
//                            c.setCompanyType(companyType.getValue());
//                            break;
//                        }
//                    }
//                }
//                if (StrUtil.isNotEmpty(c.getCompanyType())) {
//                    DictDO dictDO = saveTypeDict(companyExcel.getCompanyTypeName());
//                    if(dictDO != null){
//                        companyTypeList.add(dictDO);
//                        c.setCompanyType(dictDO.getValue());
//                    }
//                }



                switch (companyExcel.getCompanyTypeName()){
                    case "非煤矿山": c.setCompanyType("1"); break;
                    case "住建领域": c.setCompanyType("2"); break;
                    case "交通领域": c.setCompanyType("3"); break;
                    case "人密场所": c.setCompanyType("5"); break;
                    case "个私商贸": c.setCompanyType("6"); break;
                    case "危化领域": c.setCompanyType("8"); break;
                    case "工贸": c.setCompanyType("9"); break;
                    case "水利": c.setCompanyType("10"); break;
                    case "工信": c.setCompanyType("11"); break;
                    case "农业农村": c.setCompanyType("12"); break;
                    case "农机": c.setCompanyType("13"); break;
                    case "电力": c.setCompanyType("14"); break;
                    case "煤矿": c.setCompanyType("15"); break;
                    case "其他": c.setCompanyType("99"); break;
                }


                QueryWrapper<Towns> qwToken = new QueryWrapper<>();
                qwToken.eq("town_name", companyExcel.getTownName().replace("办事处",""));
                qwToken.last("limit 1");
                Towns towns = townsService.getOne(qwToken);
                if (towns!= null) {
                    c.setTownId(towns.getId());
                    c.setAreaCode(towns.getAreaCode());
                    c.setDistrictId(towns.getDistrictId());
                    District district = districtService.findById(towns.getDistrictId());
                    if(district != null){
                        c.setCityId(district.getCityId());
                        City city = cityService.findById(district.getCityId());
                        if(city != null){
                            c.setProvId(city.getProvinceId());
                        }
                    }
                }

                if (c.getTownId() == null) {
                    companyExcel.setTownName(c.getTownName() + "（未找到该乡镇）");
                    errorList.add(companyExcel);
                    continue;
                }
                boolean bl = shopService.saveOrUpdate(c);
                if(!bl){
                    companyExcel.setCompanyName(companyExcel.getCompanyName() + "（未保存成功）");
                    errorList.add(companyExcel);
                }


                //新增普通部门
                QueryWrapper<Department> qwOther = new QueryWrapper<>();
                qwOther.eq("company_id", c.getId());
                qwOther.eq("dept_type", 0);
                qwOther.last("limit 1");
                Department departmentOther = departmentService.getOne(qwOther);
                if(departmentOther == null){
                    departmentOther = new Department();
                    departmentOther.setCompanyId(c.getId());
                    departmentOther.setName("其他");
                    departmentOther.setDeptType(0);
                    departmentOther.setParentId(0);
                    departmentService.save(departmentOther);
                }

                if (oldCompany == null) {
                    //新增安全科
                    Department department = new Department();
                    department.setCompanyId(c.getId());
                    department.setName("安全科");
                    department.setDeptType(1);
                    department.setParentId(0);
                    departmentService.save(department);

                    //0  普通部门 1 - 安全科  2 - 电焊科
                    //新增安全科
                    Department department2 = new Department();
                    department2.setCompanyId(c.getId());
                    department2.setName("电焊科");
                    department2.setDeptType(2);
                    department2.setParentId(0);
                    departmentService.save(department2);
                }
            }
            if (errorList.size() > 0) {
                String fileName = System.currentTimeMillis() + "_error.xlsx";
                ExcelUtils.writeExcelToFile(ExcelType.COMPANYEXCEL, fileName, errorList, ShopNewExcel.class);
                HashMap<String, Object> map = new HashMap<>();
                map.put("code", 1);
                map.put("msg", fileName);
                return R.ok(map);
            }
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.error();
    }


    @GetMapping("/downloadErrorExcel")
    public void downloadErrorExcel(@RequestParam Map<String, Object> queryMap, HttpServletResponse response) {
        String fileName = queryMap.get("fileName").toString();
        String path = queryMap.get("path").toString();
        String property = System.getProperty("user.dir");
        String filePath = property + File.separator + path + File.separator + fileName;
        com.rzjm.exercise.common.utils.file.FileUtils.downLoadFile(response, filePath, "错误导出.xlsx");
    }

    private DictDO saveTypeDict(String pointName) {
        DictDO maxDict = dictService.getMaxValueByType("company_type");
        //新增类型
        if(StrUtil.isNotEmpty(pointName)){
            QueryWrapper<DictDO> qw = new QueryWrapper<>();
            qw.eq("type","company_type");
            qw.eq("name",pointName);
            qw.last("limit 1");
            DictDO dictDO = dictService.getOne(qw);// new DictDO();
            if(dictDO == null){
                dictDO = new DictDO();
                dictDO.setDelFlag("0");
                dictDO.setName(pointName);
                String value;
                if (maxDict != null) {
                    value = (Integer.parseInt(maxDict.getValue()) + 1) + "";
                } else {
                    value = "1";
                }
                dictDO.setValue(value);
                dictDO.setSort(new BigDecimal(value));
                dictDO.setDescription("企业类别");
                dictDO.setParentId(0L);
                dictDO.setType("company_type");

                dictService.save(dictDO);
            }
            return dictDO;
        }
        return null;
    }


    /**
     *  批量导入巡查人员信息
     * @param file
     */
    @RequestMapping(value = "/readExcelBatchAddShop", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("module:shop:importShop")
    Object readExcelBatchAddShop(@RequestParam(value="file", required = false) MultipartFile file){
        long t1 = System.currentTimeMillis();
        List<ShopExcel> list = ExcelUtils.readExcel("", ShopExcel.class, file);
        long t2 = System.currentTimeMillis();
        System.out.println(String.format("read over! cost:%sms", (t2 - t1)));
        list.forEach(b -> {
            QueryWrapper<Shop> qw = new QueryWrapper<>();
            qw.eq("id_no", b.getIdNo().replaceAll(" ",""));
            qw.last("limit 1");
            Shop shop = shopService.getOne(qw);
            if(shop == null){
                shop  = new Shop();
                String shopNo = "M" + (new Date().getTime());
                shop.setShopNo(shopNo);
                shop.setCreateTime(new Date());
                shop.setState(1);
                shop.setIdNo(b.getIdNo());
                shop.setLeaderName(b.getLeaderName());
                shop.setLeaderPhone(b.getLeaderPhone());
                shop.setAddress(b.getAddress());
                shop.setShopName(b.getShopName());
                shop.setShopType(3);

                try{
                    String fileName = "shop_qr_" + shopNo + ".jpg";
//                    String content = "{\"qrtype\":\"firework\",\"num\":\"" + shopNo + "\"}";
                    String content = "https://en.zcchengyi.com/wxmini/fire/qr?num=" + shopNo;
//                    Aes aes = new Aes();
                    int upload_type = OssUtil.TYPE_SHOP_PHOTOS;
//                    content = aes.encrypt(content);
                    System.out.println("content:  "+ content);
                    //上传头像到OSS
                    String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                    QRCodeUtilEx.createQrCodeImg(content, shop.getShopName(), null, uploadPath + "/" + img_key, true);
                    shop.setQrcodeImg(img_key);
                }catch (Exception ex){
                    ex.printStackTrace();
                }

                shopService.save(shop);
            }else{
                String shopNo = "M"+(new Date().getTime());
                if(StrUtil.isEmpty(shop.getShopNo())){
                    shop.setShopNo(shopNo);
                }

                try{
                    String fileName = "shop_qr_" + shop.getShopNo() + ".jpg";
//                    String content = "{\"qrtype\":\"firework\",\"num\":\"" + shop.getShopNo() + "\"}";
                    String content = "https://en.zcchengyi.com/wxmini/fire/qr?num=" + shop.getShopNo();
//                    Aes aes = new Aes();
                    int upload_type = OssUtil.TYPE_SHOP_PHOTOS;
//                    content = aes.encrypt(content);
                    System.out.println("content:  "+ content);
                    //上传头像到OSS
                    String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                    QRCodeUtilEx.createQrCodeImg(content, shop.getShopName(), null, uploadPath +"/"+img_key, true);
                    shop.setQrcodeImg(img_key);
                }catch (Exception ex){
                    ex.printStackTrace();
                }

                shop.setIdNo(b.getIdNo());
                shop.setLeaderName(b.getLeaderName());
                shop.setLeaderPhone(b.getLeaderPhone());
                shop.setAddress(b.getAddress());
                shop.setShopName(b.getShopName());
                shopService.updateById(shop);
            }
        });
        return R.ok();
    }

    @PostMapping(value = "/getShopListByPianquChart")
    @ResponseBody
    public R getTownDeviceTypeChart(Integer type) {
        UserDO user = getUser();

        Map<String,Object> map = new HashMap<>();
        List<Shop> shopList = shopService.selectListByColumn("pianqu_id",user.getPianquId());
        List<Integer> device0Count = new ArrayList<>();
        List<Integer> device1Count = new ArrayList<>();

        List<String> shopNames = new ArrayList<>();
        for (Shop Shop : shopList){

            shopNames.add(Shop.getShopName().replace("有限公司",""));

            Map<String,Object> map0 = new HashMap<>();
            map0.put("shop_id", Shop.getId());
            map0.put("device_type",0);
            Integer weldingCount0 = deviceWeldingService.getDeviceCountByUserId(map0);
            device0Count.add(weldingCount0);


            Map<String,Object> map1 = new HashMap<>();
            map1.put("shop_id", Shop.getId());
            map1.put("device_type",1);
            Integer weldingCount1 = deviceWeldingService.getDeviceCountByUserId(map1);
            device1Count.add(weldingCount1);
        }

        map.put("pianquName", shopNames);

        map.put("device0Count", device0Count);
        map.put("device1Count", device1Count);

        return R.ok(map);
    }

    @PostMapping(value = "/getShopListByChart")
    @ResponseBody
    public R getShopListByChart(Integer type) {
        UserDO user = getUser();

        Map<String,Object> map = new HashMap<>();
        List<Shop> shopList = shopService.selectListByColumn("id",user.getShopId());
        List<Integer> device0Count = new ArrayList<>();
        List<Integer> device1Count = new ArrayList<>();

        List<String> shopNames = new ArrayList<>();
        for (Shop Shop : shopList){

            shopNames.add(Shop.getShopName().replace("有限公司",""));

            Map<String,Object> map0 = new HashMap<>();
            map0.put("shop_id", Shop.getId());
            map0.put("device_type",0);
            Integer weldingCount0 = deviceWeldingService.getDeviceCountByUserId(map0);
            device0Count.add(weldingCount0);


            Map<String,Object> map1 = new HashMap<>();
            map1.put("shop_id", Shop.getId());
            map1.put("device_type",1);
            Integer weldingCount1 = deviceWeldingService.getDeviceCountByUserId(map1);
            device1Count.add(weldingCount1);
        }

        map.put("pianquName", shopNames);

        map.put("device0Count", device0Count);
        map.put("device1Count", device1Count);

        return R.ok(map);
    }

    /**
     * 修改
     */
    @Log("更新企业")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("module:shop:edit")
    public R update(@Valid Shop shop) {

        Pianqus pianqus = pianqusService.getById(shop.getPianquId());
        if(pianqus!= null){
            shop.setGroupId(pianqus.getJituanId());
        }

        boolean bl = shopService.updateById(shop);

        if(bl){

            if(shop.getHidShopTypes() != null){
                JSONArray hidShopTypes = JSONUtil.parseArray(shop.getHidShopTypes());
//                List<ShopType> shopTypes = JSONUtil.toList(JSONUtil.toJsonStr(hidShopTypes),ShopType.class);
                for (int i = 0 ;i<hidShopTypes.size();i++){
                    cn.hutool.json.JSONObject jsonObject = hidShopTypes.getJSONObject(i);
                    ShopType shopType = JSONUtil.toBean(jsonObject.toString(),ShopType.class);
                    if(shopType!= null){
                        QueryWrapper<ShopTypeRelation> qw = new QueryWrapper<>();
                        qw.eq("shop_id",shop.getId());
                        qw.eq("shop_type", shopType.getTypeValue());
                        qw.last("limit 1");
                        ShopTypeRelation typeRelation = shopTypeRelationService.getOne(qw);
                        if(typeRelation == null){
                            typeRelation = new ShopTypeRelation();
                            typeRelation.setShopId(shop.getId());
                            typeRelation.setShopType(shopType.getTypeValue());
                            typeRelation.setState(shopType.getIsCheck());
                            typeRelation.setTypeName(shopType.getTypeName());
                            shopTypeRelationService.save(typeRelation);
                        }else{
                            typeRelation.setState(shopType.getIsCheck());
                            typeRelation.setTypeName(shopType.getTypeName());
                            shopTypeRelationService.updateById(typeRelation);
                        }
                        if (shopType.getTypeValue() == 2  && shopType.getIsCheck() == 1){ // 车辆预约
                            addShopCarWeeks(shop);
                            addShopCarLimitTimes(shop);
                        }
                    }
                }
            }
            return R.ok();
        }
        return R.error();
    }

    /**
     *
     * * *
     * 生成车辆预约星期信息*
     * @param shop
     */
    private void addShopCarWeeks(Shop shop){
        List<CarWeeks> carWeeksList = carWeeksService.selectListByColumn("shop_id", shop.getId());
        if (carWeeksList == null || carWeeksList.size() == 0){
            String[] weekNames = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
            Integer[] weekCodes = {1,2,3,4,5,6,7};
            List<CarWeeks> saveList = new ArrayList<>();
            for (int i = 0; i < weekNames.length; i++){
                CarWeeks carWeeks = new CarWeeks();
                carWeeks.setShopId(shop.getId());
                carWeeks.setPlatformId(shop.getPlatformId());
                carWeeks.setGroupId(shop.getGroupId());
                carWeeks.setPianquId(shop.getPianquId());
                carWeeks.setState(1);
                carWeeks.setWeekName(weekNames[i]);
                carWeeks.setWeekCode(weekCodes[i]);
                saveList.add(carWeeks);
            }
            carWeeksService.saveBatch(saveList);
        }
    }

    private void addShopCarLimitTimes(Shop shop){
        List<CarLimitTimes> carLimitTimesList = carLimitTimesService.selectListByColumn("shop_id", shop.getId());
        if (carLimitTimesList == null || carLimitTimesList.size() == 0){
            String[] times = {"07:30~08:30","08:30~09:30","09:30~10:30","10:30~11:30","11:30~12:30","12:30~13:30"
                    ,"13:30~14:30","14:30~15:30","15:30~16:30","16:30~17:30","17:30~18:30","18:30~19:30"};
            List<CarLimitTimes> saveList = new ArrayList<>();
            for (int i = 0; i < times.length; i++){
                CarLimitTimes carLimitTimes = new CarLimitTimes();
                carLimitTimes.setShopId(shop.getId());
                carLimitTimes.setPlatformId(shop.getPlatformId());
                carLimitTimes.setGroupId(shop.getGroupId());
                carLimitTimes.setPianquId(shop.getPianquId());
                carLimitTimes.setLimitCarCount(2);
                carLimitTimes.setTimes(times[i]);
                saveList.add(carLimitTimes);
            }
            carLimitTimesService.saveBatch(saveList);
        }
    }
    @Log("新增企业页面")
    @GetMapping("/goBandAdmin/{shop_id}")
    @RequiresPermissions("module:shop:edit")
    String goBandAdmin(Model model, @PathVariable("shop_id") Integer shop_id) {
        Shop shop = shopService.findById(shop_id);
        model.addAttribute("shop", shop);
        List<UserDO> userDOS = userService.selectAllList();
        model.addAttribute("users", userDOS);
        return "module/shop/band_admin";
    }

    /**
     * 修改
     */
    @Log("更新企业")
    @ResponseBody
    @PostMapping("/bangAdmin")
    @RequiresPermissions("module:shop:edit")
    public R bangAdmin(@RequestParam Map<String,Object> map) {
        int admin_user_id = Integer.parseInt(map.get("admin_user_id").toString());
        int shop_id = Integer.parseInt(map.get("shop_id").toString());
        int sys_user_id = Integer.parseInt(map.get("sys_user_id").toString());
        WxUser user = wxUserService.findById(admin_user_id);
        if(user!=null){
            user.setShopId(shop_id);
            user.setUserType(1);
            wxUserService.updateById(user);
        }
        Shop shop = shopService.findById(shop_id);
        if(shop!=null){
            UserDO userDO = userService.findById(sys_user_id);
            if(userDO!=null){
                shop.setSysUserId(userDO.getUserId());
                shopService.updateById(shop);
            }
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @Log("删除企业")
    @PostMapping( "/remove")
    @ResponseBody
    @RequiresPermissions("module:shop:remove")
    public R remove(Integer id) {
        if (shopService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @Log("删除企业")
    @PostMapping("/admin/remove")
    @ResponseBody
    @RequiresPermissions("module:shop:remove")
    public R adminRemove(Integer id) {
        if (shopService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    @Log("导出列表")
    @GetMapping("/exportDeviceData")
    public void exportDeviceData(@RequestParam("shopName") String shopName,
                                @RequestParam("pianquId") String pianquId,
                                @RequestParam("shopType") String shopType,
                                @RequestParam("dateTimeRange") String dateTimeRange, HttpServletResponse response){
        UserDO userDO = getUser();
        Map<String,Object> map1 = new HashMap<>();
        String begin_time = "";
        String end_time = "";
        if(dateTimeRange != null){
            String[] range = dateTimeRange.split(" - ");
            if (range != null && range.length > 1){
                begin_time = range[0];
                end_time = range[1];
            }
        }
        if(StringUtils.isNotBlank(shopName)){
            map1.put("shop_name",shopName);
        }
        if(StringUtils.isNotBlank(shopType)){
            map1.put("shop_type",shopType);
        }
        if(StringUtils.isNotBlank(pianquId)){
            map1.put("pianqu_id",pianquId);
        }
        map1.put("isFire",0);
        if(userDO.getUserType() == 2){
            map1.put("group_id",userDO.getGroupId());
        }else if(userDO.getUserType() == 3){//分区管理员
            map1.put("pianqu_id",userDO.getPianquId());
        }
        else if(userDO.getUserType() == 12){
            map1.put("sys_user_id",userDO.getUserId());
        } else if(userDO.getUserType() == 13|| userDO.getUserType() == 14){//
            map1.put("jituan_user_id",userDO.getGroupId());
        }
        else if(userDO.getUserType() == 4 ||userDO.getUserType() == 5 || userDO.getUserType() == 6 || userDO.getUserType() == 7 || userDO.getUserType() == 10){//分厂和 巡检人员
            map1.put("id",userDO.getShopId());
        }

        List<Shop> list = new ArrayList<>();
        if(userDO.getUserType() == 0 || userDO.getUserType() == 1){
            list = shopService.getPageByAdminUserId(map1);
        }else{
            list = shopService.getPageByUserId(map1);
        }
        List<DeviceDataExcel> dataExcelList = new ArrayList<>();
        for (Shop shop : list){
            DeviceDataExcel deviceDataExcel = new DeviceDataExcel();
            deviceDataExcel.setShopName(shop.getShopName());
            deviceDataExcel.setTimeRange(dateTimeRange);
            List<Device> deviceList = deviceService.selectListByColumn("shop_id",shop.getId());
            String deviceData = "";
            for (Device device : deviceList){
                QueryWrapper<DeviceNode> nodeQueryWrapper = new QueryWrapper<>();
                nodeQueryWrapper.eq("device_id", device.getId());
                nodeQueryWrapper.eq("device_type", 2);
                List<DeviceNode> nodeList = deviceNodeService.list(nodeQueryWrapper);
                for (DeviceNode deviceNode : nodeList){
                    Map<String, Object> temperatureMap = new HashMap<>(16);
                    temperatureMap.put("device_id", device.getId());
                    temperatureMap.put("node_index", deviceNode.getNodeIndex());
                    temperatureMap.put("ins_index", deviceNode.getInsIndex());
                    temperatureMap.put("begin_time", begin_time);
                    temperatureMap.put("end_time", end_time);
                    Double avgData = shopService.getDeviceAvgDataByTime(temperatureMap);
                    deviceData += device.getDeviceName() + "(" + deviceNode.getTerminalName() + ")" + ":" + (avgData == null ? 0l : avgData) + ";";
                }
            }
            deviceDataExcel.setDeviceData(deviceData);
            dataExcelList.add(deviceDataExcel);
        }
        ExcelUtils.writeExcel(response, dataExcelList, DeviceDataExcel.class, System.currentTimeMillis() + "_设备数据.xlsx");
    }
}
